package com.su.kddq.service.user.impl;

import com.su.kddq.entity.user.User;
import com.su.kddq.security.entity.SecurityUser;
import com.su.kddq.service.courier.RoleService;
import com.su.kddq.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


/**
 * <p>
 * 自定义userDetailsService - 认证用户详情
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
@Service("userDetailsService")
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService permissionService;

    /***
     * 根据账号获取用户信息
     * @param username:
     * @return: org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            // 从数据库中取出用户信息
            User user = userService.selectByUsername(username);
            if (!StringUtils.isEmpty(user)) {
                // 返回UserDetails实现类
                com.su.kddq.security.entity.User curUser = new com.su.kddq.security.entity.User();
                curUser.setUsername(String.valueOf(user.getId()));
                curUser.setAvatar(user.getAvatar());
                curUser.setPassword(user.getPassword());
                curUser.setPhone(user.getPhone());
                List<Integer> authorities = permissionService.selectPermissionValueByUserId(user.getRid());
                SecurityUser securityUser = new SecurityUser(curUser);
                securityUser.setPermissionValue(authorities.get(0));
                return securityUser;
            }
            return null;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

}
